<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div>
    <input type="text" name="计数器" id="numberInput" value="0">
    <button id="debounceBtn" onclick="throttleClick()">节流</button>
    <button id="throttleBtn" onclick="debounceClick()">防抖</button>
  </div>

  <script>
    // document.getElementById('debounceBtn').onclick = throttle(function() {
    //   console.log('我真的被执行了')
    // })

    let _t = throttle(function() {
      console.log('我执行了节流')
    })
    function throttleClick() {
      _t();
      // fn();
    }

    let _d = debounce(function() {
      console.log('我执行了防抖')
    })
    function debounceClick() {
      _d();
    }
    // 节流函数
    function throttle(fn) {
      // 限制一定时间内只能触发一次事件，等上一次事件完成在开始下一件
      let num = 0;
      let isCan = true;
      console.log('开始', num)
      // debugger
      return function() {
        // debugger
        num ++;
        console.log('触发函数', num);
        if (!isCan) return;
        isCan = false;
        setTimeout(() => {
          console.log('timeout', num)
          fn.call(this, arguments);
          isCan = true;
        }, 2000)
      }
    }

    function debounce(fn) {
      // 指定时间内多次触发，则重新计算时间
      let lastTime;
      let timer = null;
      return function() {
        lastTime = new Date();
        if (new Date() - lastTime < 1500) {
          clearTimeout(timer);
          timer = setTimeout(() => {
            fn.call(this, arguments);
          }, 1500);
        } else {
          lastTime = new Date();
          fn.apply(this, arguments)
        }
      }
    }

    // function counter() {
    //   const input = document.getElementById('numberInput');
    //   console.log('触发函数', input);
    // }
  </script>
</body>
</html>